from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission


class TeacherPermission(BasePermission):
    """
    老师权限：只有老师可以做
    """

    def has_permission(self, request, view):
        user = request.user
        # 拿到老师组
        group = Group.objects.get(name='老师')
        # 获取用户所在的组
        groups = user.groups.all()

        return bool(user.is_superuser or group in groups)


class ActiveUserPermission(BasePermission):
    """
    当前登录用户只能操作当前的用户相关功能
    """

    def has_permission(self, request, view):
        user = request.user
        # 当前登录用户的id：user.id,  想要操作的用户的id：int(view.kwargs['pk'])
        return user.id == int(view.kwargs['pk'])


class MyBasePermission(BasePermission):
    '''
        def has_permission(self, request, view):
        if request.method in ['GET', 'HEAD', 'OPTION']:
            return True

        if request.user.is_superuser:
            return True

        if view.action == 'create' or 'update':
            user = request.user
            group = Group.objects.filter(name='老师').first()
            groups = user.groups.all()
            return user.is_superuser or group in groups

        if view.action == 'destroy':
            return request.user.is_superuser
    '''

    def has_object_permission(self, request, view, obj):
        if request.method in ['GET', 'HEAD', 'OPTION']:
            return True

        if request.user.is_superuser:
            return True

        if view.action in ['create', 'update']:
            # if view.action == 'create' or view.action == 'update':
            user = request.user
            group = Group.objects.filter(name='老师').first()
            groups = user.groups.all()
            return user.is_superuser or group in groups

        if view.action == 'destroy':
            return request.user.is_superuser


def auto_user(func):
    def f(self, request, *args, **kwargs):
        request.POST._mutable = True
        request.data['user'] = str(request.user.id)
        return func(self, request, *args, **kwargs)

    return f
